package com.tide.crm.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


public class HttpClientUtils {

	public static String doPost(String url, String data) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(20000)
				.setConnectionRequestTimeout(10000).build();
		httpPost.setConfig(requestConfig);
		String context = StringUtils.EMPTY;
		if (!StringUtils.isEmpty(data)) {
			StringEntity body = new StringEntity(data, "utf-8");
			httpPost.setEntity(body);
		}
		// 设置回调接口接收的消息头
		httpPost.addHeader("Content-Type", "application/json");
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			context = EntityUtils.toString(entity, HTTP.UTF_8);
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			try {
				response.close();
				httpPost.abort();
				httpClient.close();
			} catch (Exception e) {
				e.getStackTrace();
			}
		}
		return context;
	}

	public static String doGet(String url,String data) throws Exception {
		
		String result = "";
		// 获取http客户端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通过httpget方式来实现我们的get请求
		HttpGet httpGet = new HttpGet(url);
		// 通过client调用execute方法，得到我们的执行结果就是一个response，所有的数据都封装在response里面了
		CloseableHttpResponse Response = client.execute(httpGet);
		// HttpEntity
		// 是一个中间的桥梁，在httpClient里面，是连接我们的请求与响应的一个中间桥梁，所有的请求参数都是通过HttpEntity携带过去的
		// 所有的响应的数据，也全部都是封装在HttpEntity里面
		HttpEntity entity = Response.getEntity();
		// 通过EntityUtils 来将我们的数据转换成字符串
		result = EntityUtils.toString(entity, "UTF-8");
		// 关闭
		Response.close();
		return result;
	}
	
	
	public static void doPost(String url,Map<String,Object> params) throws IOException {
		String imei ="867186032552993";
		// 获取http客户端
		CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);  // 接口
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); // 设置回调接口接收的消息头
        String body = JsonMapper.toJson(params);  //必须是json模式的 post      
        StringEntity entity;
        entity = new StringEntity(body);
        entity.setContentType("image/png");

        httpPost.setEntity(entity);
     	CloseableHttpResponse response = null;
     	response = httpClient.execute(httpPost);
     			

        InputStream inputStream = response.getEntity().getContent();
        String name = imei+".jpg";
        saveToImgByInputStream(inputStream,"E:\\",name);  //保存图片
	}
	
	/**
     * 将二进制转换成文件保存
     * @param instreams 二进制流
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return 
     *      1：保存正常
     *      0：保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
        int stateInt = 1;
        if(instreams != null){
            try {
                File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();                
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("scene", "from=qrcode&id=1840259830497280");
		params.put("page", "pages/merchant/merchant"); //位置
        params.put("width", 430);
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=25_aZX3ziEwY_u6npLm79iYvd2-HGBOK605O5V7biI4YZdYqXloiDCa3RVjZDaLdtuNW2xrjumrKHH06MJV28cvKMXcJz_9Of996Pouus561WHKMUFs4EVhtGS4967uOJ-PtMFqwNhu3OTyuT2oOKIeAHAEAY";
        
        HttpClientUtils.doPost(url, params);
	}

}
